<!--
  * 盘点单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="{ sm: 7, md: 6 }">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="盘点单号" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.no" placeholder="盘点单号" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="订单状态" class="smart-margin-bottom0">
            <EnumSelect enum-name="CHECK_STATUS_ENUM" v-model:value="queryForm.check_status" placeholder="订单状态" @submit="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="盘点人" class="smart-margin-bottom0">
            <a-input v-model:value.trim="queryForm.check_user" placeholder="请输入盘点人" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <!-- <a-button @click="addGoods" type="primary" v-privilege="'stocktaking:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>

        <a-button @click="onExport" type="primary" v-privilege="'stocktaking:export'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button> -->
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{}">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'no'">
            <CopyText :text="text">
              <a @click="detail(record)">{{ text }}</a>
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'check_status'">
            <span>{{ getDescByValue('CHECK_STATUS_ENUM', text) }}</span>
          </template>
          <template v-if="column.dataIndex === 'py_num'">
            <span :style="{ color: record.py_color }">{{ text }}</span>
          </template>
          <template v-if="column.dataIndex === 'py_money'">
            <span :style="{ color: record.py_color }">{{ text }}</span>
          </template>
          <template v-if="column.dataIndex === 'pk_num'">
            <span :style="{ color: record.pk_color }">{{ text }}</span>
          </template>
          <template v-if="column.dataIndex === 'pk_money'">
            <span :style="{ color: record.pk_color }">{{ text }}</span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="detail(record)" type="link" style="color: #97999c">详情</a-button>
              <!-- <a-button @click="cancel(record)" type="link" danger v-if="[CHECK_STATUS_ENUM.INVENTORIED.value, CHECK_STATUS_ENUM.IN_PROGRESS.value].includes(record.check_status)">取消盘点</a-button>
              <a-button @click="deleteData(record.id, record.no)" type="link" danger v-if="record.check_status === CHECK_STATUS_ENUM.CANCELLED.value">删除</a-button>
              <a-button @click="print(record)" type="link">打印</a-button>
              <a-button @click="onExportGoods(record)" type="link" v-privilege="'stocktaking:export'">导出</a-button> -->
            </div>
          </template>
        </template>
      </a-table>
    </div>

    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
    <stocktakingPrintModal ref="printRef" />
    <StocktakingFormModal ref="formModal" @reload-list="queryData" />
    <!---------- 详情 begin ----------->
    <StocktakingDetailsModal ref="detailRef" @reload-list="queryData" />
    <!---------- 详情 end ----------->
  </a-card>
</template>
<script setup lang="ts">
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import stocktakingPrintModal from './components/stocktaking-print-modal.vue'
import StocktakingDetailsModal from './components/stocktaking-details-modal.vue'
import StocktakingFormModal from './components/stocktaking-form-modal.vue'
import { checkStockApi } from '@/api/business/storage/stocktaking-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import TableOperator from '@/components/support/table-operator/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import _ from 'lodash'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useResize } from '@/hooks/web/use-resize-hook'
import { CHECK_STATUS_ENUM } from '@/constants/business/storage/stocktaking/stocktsking-const'
import { Modal, message } from 'ant-design-vue'
const { getDescByValue } = useEnums()

// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = ref([
  {
    title: '盘点单号',
    dataIndex: 'no',
    width: 180
  },
  {
    title: '盘点状态',
    dataIndex: 'check_status',
    width: 80
  },
  {
    title: '盘盈数量',
    dataIndex: 'py_num',
    width: 80
  },
  {
    title: '盘盈金额',
    dataIndex: 'py_money',
    width: 80
  },
  {
    title: '盘亏数量',
    dataIndex: 'pk_num',
    width: 80
  },
  {
    title: '盘亏金额',
    dataIndex: 'pk_money',
    width: 80
  },
  {
    title: '盘点人',
    dataIndex: ['check_user', 'username'],
    width: 120
  },
  {
    title: '盘点时间',
    dataIndex: 'check_time',
    width: 120
  },
  {
    title: '创建人',
    dataIndex: ['create_user', 'username'],
    width: 120
  },
  {
    title: '单据日期',
    dataIndex: 'create_time',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: 80
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const { queryForm, tableData, tableLoading, total, resetQuery, onSearch, queryData, deleteData } = useQuery({
  fetchDataApi: async (params) => {
    const res = await checkStockApi.queryList(params)
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  fetchDeleteApi: async (id) => {
    const res = await checkStockApi.delete({ id })
    return !!res
  },
  queryFormFilter: {
    no: '',
    create_time: DEFAULT_TIME_RANGE.value,
    check_status: null,
    check_user: ''
  },
  queryFormOp: {
    no: QUERY_FORM_OP['模糊查询'],
    create_time: QUERY_FORM_OP['范围查询'],
    check_status: QUERY_FORM_OP['全等查询'],
    check_user: QUERY_FORM_OP['模糊查询']
  }
})

onMounted(queryData)

// ---------------------------- 添加/修改 ----------------------------
const formModal = ref()

function addGoods(goodsData) {
  formModal.value.showDrawer(goodsData)
}

// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (goodsData) => {
  detailRef.value.showDrawer(goodsData)
}
// 打印
const printRef = ref()

const print = (goodsData) => {
  printRef.value.showDrawer(goodsData)
}
// 取消
function cancel(record) {
  Modal.confirm({
    title: '确定取消该盘点任务吗？',
    onOk: async () => {
      try {
        const res = await checkStockApi.cancel({ id: record.id })
        message.success(res.msg)
        queryData()
      } catch (error) {
        message.error(error.msg)
      }
    }
  })
}
// ---------------------------- 单个导出 ----------------------------

function onExportGoods(record) {
  checkStockApi.exportExcel({ id: record.id })
}
// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const filter = {
    no: queryForm.value.no,
    create_time: queryForm.value.create_time,
    check_status: queryForm.value.check_status,
    check_user: queryForm.value.check_user
  }
  const op = {
    no: QUERY_FORM_OP['模糊查询'],
    create_time: QUERY_FORM_OP['范围查询'],
    check_status: QUERY_FORM_OP['全等查询'],
    check_user: QUERY_FORM_OP['模糊查询']
  }
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(op)
  }
  checkStockApi.exportXlsx(data)
}
</script>
